package cn.jekun.shop.web.service;

import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.DateJsonValueProcessor;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jekun.component.base.bean.Page;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.ErpMyLocation;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.shop.common.service.ShopBaseService;
@Service(LocationService.BEAN_NAME)
public class LocationService extends ShopBaseService{
	public static final String BEAN_NAME = "cn.jekun.shop.web.service.LocationService";
	@Override
	public String getNamespace() {
		return "ERP_MY_LOCATION";
	}
	@SuppressWarnings("unchecked")
	@Transactional
	public JSONObject save(@ErpMyLocation.AnnoLongitude String lng,@ErpMyLocation.AnnoLatitude String lat,@ErpMyLocation.AnnoDes()String memo,@RsUser.AnnoUserId() String userId,@ErpMyLocation.AnnoDef()String def){
		JSONObject jsonObject = new JSONObject();
		Page page = new Page();
		List resultList = new ArrayList();
		Map formMap = new HashMap();
		if (StringUtils.isBlank(lng)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"经度不能为空");
		}
		if (StringUtils.isBlank(lat)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"纬度不能为空");
		}
		if (StringUtils.isBlank(memo)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"地址描述不能为空");
		}
		if (StringUtils.isBlank(userId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户代码不能为空");
		}
		if (StringUtils.isBlank(def)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"默认值字段不能为空");
		}
		Map totalMap = new HashMap();
		totalMap.put(ErpMyLocation.COL_USER_ID, userId);
		SqlUtis.prepareSql(totalMap, "", SqlUtis.getSQL(totalMap, "a."
				+ ErpMyLocation.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ));
		List list = this.list(totalMap);
		if(list.size()>=5){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"我的位置不能超过5条");
		}
		Map latLngMap = new HashMap();
		latLngMap.put(ErpMyLocation.COL_LATITUDE,lat);
		latLngMap.put(ErpMyLocation.COL_LONGITUDE, lng);
		SqlUtis.prepareSql(latLngMap, "", SqlUtis.getSQL(latLngMap, "a."
				+ ErpMyLocation.COL_LATITUDE, Types.VARCHAR,SqlUtis.EQ),
				SqlUtis.getSQLRequired(latLngMap, "a."
						+ ErpMyLocation.COL_LONGITUDE, Types.VARCHAR,SqlUtis.EQ));
		boolean flag = this.exists(latLngMap);
		if(flag){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"此位置已存在");
		}
		//如果添加我的位置为默认位置则需要更新该用户对应的其他所有位置设置为非默认
		if(def.equals("1")){
			Map tempLocationMap = new HashMap();
			tempLocationMap.put(ErpMyLocation.COL_USER_ID, userId);
			SqlUtis.prepareSql(tempLocationMap, "", SqlUtis.getSQL(tempLocationMap, "a."
					+ ErpMyLocation.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ));
			List<ErpMyLocation> tempList = this.list(tempLocationMap);
			if(tempList != null){
				ErpMyLocation tempLocation = new ErpMyLocation();
				tempLocation.setDef("0");
				tempLocationMap.put("erpMyLocation", tempLocation);
				SqlUtis.prepareSql(tempLocationMap, "", SqlUtis.getSQL(tempLocationMap, "a."
						+ ErpMyLocation.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ)
						);
				this.update(tempLocationMap);
			}
		}
		ErpMyLocation location = new ErpMyLocation();
		location.setDes(memo);
		location.setUserId(userId);
		location.setLongitude(Double.parseDouble(lng));
		location.setLatitude(Double.parseDouble(lat));
		location.setDef(def);
		formMap.put("erpMyLocation", location);
		String returnId = this.insert(formMap).toString();
		if(returnId==null){
			return executeRerutnFail(jsonObject);
		}else{
		return executeRerutn(jsonObject);
		}
	}
	@SuppressWarnings("unchecked")
	@Transactional
	public JSONObject del(@ErpMyLocation.AnnoLocationId String locationId){
		JSONObject jsonObject = new JSONObject();
		Page page = new Page();
		 List resultList = new ArrayList();
		 Map formMap = new HashMap();
		if (StringUtils.isBlank(locationId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"位置编码不能为空");
		}
		formMap.put(ErpMyLocation.COL_LOCATION_ID, locationId);
		SqlUtis.prepareSql(formMap, "", SqlUtis.getSQL(formMap, "a."
				+ ErpMyLocation.COL_LOCATION_ID, Types.VARCHAR,SqlUtis.EQ));
		int total = this.delete(formMap);//返回删除的条数
		if(total == 0){
			return executeRerutnFail(jsonObject);
		}else{
		return executeRerutn(jsonObject);
		}
		
	}
	
	@SuppressWarnings("unchecked")
	public JSONObject load(@ErpMyLocation.AnnoLocationId String locationId){
		JSONObject jsonObject = new JSONObject();
		Page page = new Page();
		 List resultList = new ArrayList();
		 Map formMap = new HashMap();
		if (StringUtils.isBlank(locationId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"位置编码不能为空");
		}
		formMap.put(ErpMyLocation.COL_LOCATION_ID, locationId);
		SqlUtis.prepareSql(formMap, "", SqlUtis.getSQL(formMap, "a."
				+ ErpMyLocation.COL_LOCATION_ID, Types.VARCHAR,SqlUtis.EQ));
		ErpMyLocation location = this.one(formMap);
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));
		JSONObject json =  JSONObject.fromObject(location, jsonConfig);
		jsonObject.put("MyLocation", json);
		return executeRerutn(jsonObject);
	}
	@SuppressWarnings("unchecked")
	public JSONObject query(int pageSize,int currentPage,@RsUser.AnnoUserId String userId){
		if (StringUtils.isBlank(Integer.toString(pageSize))) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"页大小不能为空");
		}
		if (StringUtils.isBlank(Integer.toString(currentPage))) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"当前页不能为空");
		}
		if (StringUtils.isBlank(Integer.toString(currentPage))) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户代码不能为空");
		}
		JSONObject jsonObject = new JSONObject();
		Page page = new Page();
		List resultList = new ArrayList();
		Map formMap = new HashMap();
		page.setPageSize(pageSize);
		page.setPageNumber(currentPage);
		formMap.put(ErpMyLocation.COL_USER_ID, userId);
		SqlUtis.prepareSql(formMap, "", SqlUtis.getSQL(formMap, "a."
				+ ErpMyLocation.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ));
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd")); 
		JSONArray jsonArray = JSONArray.fromObject(this.list(formMap, page), jsonConfig);
		jsonObject.put("locationList", jsonArray);
		jsonObject.put("totals", page.getTotalCount());
		return executeRerutn(jsonObject);
		
	}
	@SuppressWarnings("unchecked")
	@Transactional
	public JSONObject update(@ErpMyLocation.AnnoLocationId String locationId,@ErpMyLocation.AnnoDef String def,@RsUser.AnnoUserId String userId){
		JSONObject jsonObject = new JSONObject();
		Page page = new Page();
		List resultList = new ArrayList();
		Map formMap = new HashMap();
		if (StringUtils.isBlank(locationId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"位置编码不能为空");
		}
		/*if (StringUtils.isBlank(lng)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"经度不能为空");
		}
		if (StringUtils.isBlank(lat)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"纬度不能为空");
		}
		if (StringUtils.isBlank(memo)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"地址描述不能为空");
		}*/
		if (StringUtils.isBlank(def)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"默认值字段不能为空");
		}
		if (StringUtils.isBlank(userId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户编码不能为空");
		}
		//如果添加我的位置为默认位置则需要更新该用户对应的其他所有位置设置为非默认
		if(def.equals("1")){
			Map tempLocationMap = new HashMap();
			tempLocationMap.put(ErpMyLocation.COL_USER_ID, userId);
			SqlUtis.prepareSql(tempLocationMap, "", SqlUtis.getSQLRequired(tempLocationMap, "a."
					+ ErpMyLocation.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ));
			List<ErpMyLocation> tempList = this.list(tempLocationMap);
			if(tempList != null){
				ErpMyLocation tempLocation = new ErpMyLocation();
				tempLocation.setDef("0");
				tempLocationMap.put("erpMyLocation", tempLocation);
				SqlUtis.prepareSql(tempLocationMap, "", SqlUtis.getSQLRequired(tempLocationMap, "a."
						+ ErpMyLocation.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ)
						);
				this.update(tempLocationMap);
			}
		}
		formMap.put(ErpMyLocation.COL_LOCATION_ID, locationId);
		ErpMyLocation location = new ErpMyLocation();
		/*location.setDes(memo);
		location.setLatitude(Double.parseDouble(lat));
		location.setLongitude(Double.parseDouble(lng));*/
		location.setDef(def);
		formMap.put("erpMyLocation", location);
		SqlUtis.prepareSql(formMap, 
				SqlUtis.getSQL(formMap, "a."+ErpMyLocation.COL_LOCATION_ID, Types.VARCHAR,SqlUtis.EQ));
		int total = this.update(formMap);//返回更新的条数
		if(total==0){
			return executeRerutnFail(jsonObject);
		}else{
			return executeRerutn(jsonObject);
		}
		
	}

}
